package com.tom.demo.array;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Test169_MajorityElement {

    public static void main(String[] args) {
        System.out.println(majorityElement_03(new int[]{3, 2, 3}));
        System.out.println(majorityElement_03(new int[]{2, 2, 1, 1, 1, 2, 2}));
    }

    // 哈希表统计
    public static int majorityElement_01(int[] nums) {
        if (nums == null) {
            return -1;
        }
        if (nums.length == 1) {
            return nums[0];
        }

        Map<Integer, Integer> map = new HashMap<>();
        int n = nums.length / 2;

        for (int i : nums) {
            if (map.containsKey(i)) {
                map.put(i, map.get(i) + 1);
            } else {
                map.put(i, 1);
            }
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > n) {
                return entry.getKey();
            }
        }
        return -1;
    }

    // 排序取位于中间位置的数据
    public static int majorityElement_02(int[] nums) {
        if (nums == null) {
            return -1;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }

    // 投票算法
    public static int majorityElement_03(int[] nums) {
        int votes = 0, x = 0;
        for (int num : nums) {
            if (votes == 0) {
                x = num;
                votes++;
                continue;
            }
            if (num == x) {
                votes++;
            } else {
                votes--;
            }
        }
        return x;
    }

}
